package TwoPointers;

public class _80_RemoveDuplicatesfromSortedArrayII {
    public int removeDuplicates(int[] nums) {
        if(nums.length==0) return 0;
        int length = 0;
        boolean dupli = false;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                if (!dupli) {
                    dupli = true;
                    nums[length++] = nums[i];
                    nums[length++] = nums[i + 1];
                }
            } else {
                if (dupli) {
                    dupli = false;
                } else {
                    nums[length++] = nums[i];
                }
            }
        }
        //the last num
        if (dupli) {
            dupli = false;
        } else {
            nums[length++] = nums[nums.length - 1];
        }
        return length;
    }

    //more precise,use the new array's num to handle
    public int removeDuplicates_2(int[] nums) {
        if (nums == null)   return 0;
        if (nums.length <= 2)   return nums.length;
        int count = 1;
        for(int i = 2; i < nums.length; i++) {
            if (nums[count] != nums[i] || nums[count - 1] != nums[i]) {
                nums[++count] = nums[i];
            }
        }
        return count + 1;
    }
}
